package com.zhiwei.msf.gateway.config;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandProperties;
import org.springframework.cloud.netflix.hystrix.HystrixCircuitBreakerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.function.Function;

/**
 * function: 断路器配置
 * author: zhiwei_yang
 * time: 2020/2/12-12:20
 */
@Configuration
public class CircuitBreakerConfig {

    /**
     * 自定义断路器默认配置
     *
     * @return
     */
    @Bean
    public HystrixCircuitBreakerFactory defaultConfig() {
        HystrixCommandProperties.Setter setter = HystrixCommandProperties.Setter()
                .withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.THREAD) //线程池隔离策略
                .withFallbackEnabled(true)//是否启用降级
                .withFallbackIsolationSemaphoreMaxConcurrentRequests(100)//设置getFallback并发请求信号量，如果超过信号量值，不会再走直getFallback而直接快速失败
                .withExecutionIsolationThreadInterruptOnFutureCancel(true)
                .withExecutionIsolationThreadInterruptOnTimeout(true)//当隔离策略为Thread时候，当线程超时时，是否中断处理
                .withExecutionTimeoutEnabled(true)//是否启用超时机制
                .withExecutionTimeoutInMilliseconds(10000);//超时时间设置

        Function<String, HystrixCommand.Setter> defaultConfiguration = new Function<String, HystrixCommand.Setter>() {
            @Override
            public HystrixCommand.Setter apply(String s) {
                return HystrixCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("xxxxx"))
                        .andCommandPropertiesDefaults(setter);
            }
        };

        HystrixCircuitBreakerFactory hystrixCircuitBreakerFactory = new HystrixCircuitBreakerFactory();
        hystrixCircuitBreakerFactory.configureDefault(defaultConfiguration);

        return hystrixCircuitBreakerFactory;
    }
}